# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : nacos_handle.py
# Time       ：2025/2/21 09:39
# Description：
"""
import json
import nacos
from public_tools.common_vars import log


class NacosClient:
    namespace_map: dict = {
        "beta06": "0dc0ac80-8a40-4f32-a936-1b030c228800",
        "sit": "efb889b6-8005-430d-8c71-02c8356ff28a",
        "migu": "3126419b-ca82-4d37-ab99-b458e1d7c15b"
    }

    def __init__(self, service_group, env="beta08"):
        """
        """
        self.client = nacos.NacosClient(
            "10.86.3.70",
            namespace=self.namespace_map.get(env),
            username="nacos",
            password="nacos"
        )
        self.service_group = service_group

    def load_conf(self, data_id):
        try:
            content = json.loads(self.client.get_config(data_id=data_id, group=self.service_group, no_snapshot=True))
            return content
        except Exception as e:
            log.error(f"请检查该dataId在当前环境是否存在，以及数据格式(json)是否正确: {e}")
            return {}

    def load_http_data(self, data_id):
        content = json.loads(self.client.get_config(data_id=data_id, group=self.service_group, no_snapshot=True))
        data = content.get("data")
        _json = content.get("json")
        params = content.get("params")
        return data, _json, params

    def load_confs(self, group):
        return self.client.get_configs(group=group)

    def add_conf_watcher(self, data_id, group, callback):
        self.client.add_config_watcher(data_id=data_id, group=group, cb=callback)


if __name__ == '__main__':
    client = NacosClient("CGSession")

    data_stream = client.load_conf("case01")
    log.info(f"根据id读取配置: {data_stream}")

    data_stream2 = client.load_confs("CGSession")
    log.info(f"根据group读取配置: {data_stream2}")
